package com.scrum.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.scrum.Object.Catalog;
import com.scrum.Object.File_Process;
import com.scrum.Object.Post;

/**
 * Servlet implementation class Update_Post
 */
@WebServlet("/post/update_post")
@MultipartConfig
public class Update_Post extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Update_Post() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("dfasdfas");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filepath = getServletContext().getInitParameter("post_file_upload"); 
		String post_id = request.getParameter("postid");
		Post post = null;
		try {
			post = Post.getPostById(Integer.parseInt(post_id));
		} catch (NumberFormatException | ClassNotFoundException | SQLException e1) {
			e1.printStackTrace();
		}
		String filename;
		Part filePart = request.getPart("browse_image"); // Retrieves <input type="file" name="file">
		try{
		filename = File_Process.getFilename(filePart);
		
	    InputStream filecontent = filePart.getInputStream();
	    OutputStream  outputStream = new FileOutputStream(new File(filepath+ File.separator + filename));
	    int read = 0;
	    byte[] bytes = new byte[1024];

		while ((read = filecontent.read(bytes)) != -1) {
			outputStream.write(bytes, 0, read);
		}
	    }catch(Exception ex){
	    	filename = post.getImage();
	    }
		String title = request.getParameter("title");
		String catalog = request.getParameter("catalog");
		String description = request.getParameter("description");
		//usersignin
		int user_id = 1;
		try {
		int catalog_id = Catalog.getId(catalog);
		if (catalog_id != -1){
			
				post.update(title, catalog_id, filename, description);
					response.sendRedirect("updatepost.jsp?postid="+post_id);
		}
			} catch (ClassNotFoundException | SQLException e) {
				e.printStackTrace();
			}
	
//			
		
		}

}
